<?php
class Admin_Permissions  extends Admin_Controller{
	private $namespace = 'permissions';
	function __construct(){
		parent::__construct();
		$this->load->model('groups_m');
		$this->load->model('permissions_m');
		$this->check_permissions();
	}
	
	public function index(){
		$group_parent = $this->groups_m->group_parent($this->current_user->group_by);
		$group_parent_string = join(',',$group_parent);
		
		$param['not_name'] = array('admin',$group_parent_string,'customer');
		$model = $this->groups_m->get_all($param);
		
		$this->template
			->set('model',$model)
			->build($this->controller.'/'.$this->method);
	}
	
	public function edit($id){
		
		$module_active = $this->permissions_m->get_module_all(1);
		$module_per = $this->permissions_m->get_group($id);//module hien tai cua group
		//print_r($module_active);
		//print_r($module_per);exit;
		//update  $module_active from $module_per
		$result = array();
		foreach($module_active as $mod=>$mod_value){
			$item = new stdClass();
			$item->name = $mod;
			$item->checked  = false;
			foreach($module_per as $p=>$p_value){
				if($mod == $p){
					$module_active[$mod] = 1;
					$item->checked  = "checked";
				}
			}
			$item->value = $module_active[$mod];
			$result[] = $item;
		}
		
		$model = (array)$this->groups_m->get($id);
		
		$type =  substr($this->input->post('btnAction'), 0);
		
		if ( type_post($type) ) {
				$model =  $this->input->post();
				$skip = array('btnAction');
				foreach($skip as $obj){
				if(array_key_exists($obj,$model)){
					unset($model[$obj]); 
					}
				}
				$this->permissions_m->insert($id,$model); 
				//xoa cache tuong ung voi group
				$this->kunkuncache->delete('permissions/groups_top_'.$id);
				$this->kunkuncache->delete('permissions/groups_left_'.$id);
				$this->redirect_to_action($this->method,$this->namespace,$type,$id);			
		}
		$this->action = 'save|javascript:void(0)|'.lang('global:save') ;
		$this->view(array('model'=>$model,'modules'=>$result,'action'=>$this->action));
	}	
}